import React, { useEffect, useRef } from 'react';
import Portal from './Portal';
import { FaCircleXmark } from 'react-icons/fa6';
import styles from './Dialog.module.css';

const Dialog = ({
  isOpen,
  onClose,
  title,
  children,
  footer,
  className = '',
  size = 'medium', // small, medium, large
  showCloseButton = true,
  closeOnOverlayClick = true,
  closeOnEscape = true
}) => {
  const dialogRef = useRef(null);

  // 处理ESC键关闭
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (closeOnEscape && event.key === 'Escape' && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = 'auto';
    };
  }, [isOpen, onClose, closeOnEscape]);

  // 处理点击遮罩层关闭
  const handleOverlayClick = (event) => {
    if (closeOnOverlayClick && event.target === event.currentTarget) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <Portal>
      <div className={styles.mask}></div>
      <div className={styles.overlay} onClick={handleOverlayClick}>
        <div 
          ref={dialogRef}
          className={`${styles.dialog} ${styles[size]} ${className}`}
        >
          {title && (
            <div className={styles.header}>
              <h3 className={styles.title}>
                {title}
              </h3>
              {showCloseButton && (
                <button
                  className={styles.closeButton}
                  onClick={onClose}
                >
                  ×
                </button>
              )}
            </div>
          )}
          
          <div className={styles.content}>
            {children}
          </div>
          
          {footer && (
            <div className={styles.footer}>
              {footer}
            </div>
          )}
        </div>
      </div>
    </Portal>
  );
};

export default Dialog;
